# -*- coding: utf-8 -*-

import base
import json,uuid,time,traceback,datetime
import requests
import pika,logging
from main.settings import REDIS_STORE_URL,RABBITMQ_HOST_URL,RABBITMQ_USER,RABBITMQ_USER_PASSWORD,RABBITMQ_PORT
# logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# logger = logging.getLogger(__name__)
# logger = logging.getLogger(__name__)
# logger.setLevel(level = logging.INFO)
# handler = logging.FileHandler("rabbitmq.log")
# handler.setLevel(logging.INFO)
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# handler.setFormatter(formatter)
# logger.addHandler(handler)

# logger.info("Start print log")

class MqServer(object):
    """
    构造请求数据
    """
    def __init__(self,task_id,area_id):
        self.user=RABBITMQ_USER
        self.pwd=RABBITMQ_USER_PASSWORD
        self.host=RABBITMQ_HOST_URL
        self.port=RABBITMQ_PORT
        self.virtual_host='/'
        self.exchange = 'rb-topic'
        self.routing_key = 'message.wechat'#不同的主题，使用不同的key
        self.queue='message-wechat'#不同的消息类型，使用不同的队列
        self.task_id = task_id
        self.area_id = area_id
    
    #接收消息
    def start(self):
        try:
            # self.linshi_que()
            # self.durable_que()#模板消息例子
            # self.text_durable_que()#文本消息例子
            # self.images_durable_que()#图片消息例子

            self.qrcode_durable_que()#生成带参数二维码
        except:
            traceback.print_exc()
    
    #带参数二维码
    def qrcode_durable_que(self):
        credentials = pika.PlainCredentials(self.user, self.pwd)  # mq用户名和密码
        # 虚拟队列需要指定参数 virtual_host，如果是默认的可以不填。
        connection = pika.BlockingConnection(pika.ConnectionParameters(host = self.host,port = self.port,virtual_host = self.virtual_host,credentials = credentials))
        channel=connection.channel()
        # 声明消息队列，消息将在这个队列传递，如不存在，则创建.
        # queue 声明持久化
        # durable = True 代表消息队列持久化存储，False 非持久化存储
        result = channel.queue_declare(queue = self.queue,durable = True)
        

        currtime = datetime.datetime.now()
        currtime = currtime.strftime("%Y-%m-%d %H:%M:%S")

        projectjson = {
            'project_id':10,
            'app_id':'wxff92ea6443261eee',
            'secret':'1e62fba4dac15df3ffe12373a49a89dc',
            'redis_url':REDIS_STORE_URL,#动态设置
        }
        msgtype = {
            'code':'wechat',
            'type':'createqrcode',
            'title':'创建二维码',
            'url':None,
            'mini_program':None,
            'template_id':'m7XCd6F0e3CGC_if1U7p4pZXckLObzYXlLA0h_02uVk'
        }
        messagejson = {
            'action_name':'QR_LIMIT_SCENE',
            'action_info':{
                'scene': {'scene_id': '8c65497aeb42e71a385b0194e683182c'}
            }
        }
        touser = 'orN6Y0WQl5X9dnAUD19KVAV5Vy9s'
        message = json.dumps({'projectjson':projectjson,'createtime':currtime,'messagejson':messagejson,'touser':touser,'msgtype':msgtype})
        print(message)
        # logging.info('------msg----')
        # logging.info(message)
        # 声明exchange，由exchange指定消息在哪个队列传递，如不存在，则创建。durable = True 代表exchange持久化存储，False 非持久化存储
        channel.exchange_declare(exchange = self.exchange,durable = True, exchange_type='topic')
        # channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message,properties=pika.BasicProperties(delivery_mode = 2))
        channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message)
        connection.close()

    #图片消息队列
    def images_durable_que(self):
        credentials = pika.PlainCredentials(self.user, self.pwd)  # mq用户名和密码
        # 虚拟队列需要指定参数 virtual_host，如果是默认的可以不填。
        connection = pika.BlockingConnection(pika.ConnectionParameters(host = self.host,port = self.port,virtual_host = self.virtual_host,credentials = credentials))
        channel=connection.channel()
        # 声明消息队列，消息将在这个队列传递，如不存在，则创建.
        # queue 声明持久化
        # durable = True 代表消息队列持久化存储，False 非持久化存储
        result = channel.queue_declare(queue = self.queue,durable = True)
        

        currtime = datetime.datetime.now()
        currtime = currtime.strftime("%Y-%m-%d %H:%M:%S")

        projectjson = {
            'project_id':10,
            'app_id':'wxff92ea6443261eee',
            'secret':'1e62fba4dac15df3ffe12373a49a89dc',
            'redis_url':REDIS_STORE_URL,#动态设置
        }
        msgtype = {
            'code':'wechat',
            'type':'image',
            'title':'文本消息',
            'url':None,
            'mini_program':None,
            'template_id':'m7XCd6F0e3CGC_if1U7p4pZXckLObzYXlLA0h_02uVk'
        }
        messagejson = {
            'media_id':'5OlriStH7UNVEvbGwYg9hsHQVsLA1SmNYsBKRhCbsTE'
        }
        touser = 'orN6Y0WQl5X9dnAUD19KVAV5Vy9s'
        message = json.dumps({'projectjson':projectjson,'createtime':currtime,'messagejson':messagejson,'touser':touser,'msgtype':msgtype})
        print(message)
        # logging.info('------msg----')
        # logging.info(message)
        # 声明exchange，由exchange指定消息在哪个队列传递，如不存在，则创建。durable = True 代表exchange持久化存储，False 非持久化存储
        channel.exchange_declare(exchange = self.exchange,durable = True, exchange_type='topic')
        # channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message,properties=pika.BasicProperties(delivery_mode = 2))
        channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message)
        connection.close()

    #文本消息
    def text_durable_que(self):
        credentials = pika.PlainCredentials(self.user, self.pwd)  # mq用户名和密码
        # 虚拟队列需要指定参数 virtual_host，如果是默认的可以不填。
        connection = pika.BlockingConnection(pika.ConnectionParameters(host = self.host,port = self.port,virtual_host = self.virtual_host,credentials = credentials))
        channel=connection.channel()
        # 声明消息队列，消息将在这个队列传递，如不存在，则创建.
        # queue 声明持久化
        # durable = True 代表消息队列持久化存储，False 非持久化存储
        result = channel.queue_declare(queue = self.queue,durable = True)
        

        currtime = datetime.datetime.now()
        currtime = currtime.strftime("%Y-%m-%d %H:%M:%S")

        projectjson = {
            'project_id':10,
            'app_id':'wxff92ea6443261eee',
            'secret':'1e62fba4dac15df3ffe12373a49a89dc',
            'redis_url':REDIS_STORE_URL,#动态设置
        }
        msgtype = {
            'code':'wechat',
            'type':'text',
            'title':'文本消息',
            'url':None,
            'mini_program':None,
            'template_id':'m7XCd6F0e3CGC_if1U7p4pZXckLObzYXlLA0h_02uVk'
        }
        messagejson = {
            'content':'\uE312海报正在生成中，请稍后...'
        }
        touser = 'orN6Y0WQl5X9dnAUD19KVAV5Vy9s'
        message = json.dumps({'projectjson':projectjson,'createtime':currtime,'messagejson':messagejson,'touser':touser,'msgtype':msgtype})
        print(message)
        # logging.info('------msg----')
        # logging.info(message)
        # 声明exchange，由exchange指定消息在哪个队列传递，如不存在，则创建。durable = True 代表exchange持久化存储，False 非持久化存储
        channel.exchange_declare(exchange = self.exchange,durable = True, exchange_type='topic')
        # channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message,properties=pika.BasicProperties(delivery_mode = 2))
        channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message)
        connection.close()

    #持久化rabbitmq
    def durable_que(self):
        credentials = pika.PlainCredentials(self.user, self.pwd)  # mq用户名和密码
        # 虚拟队列需要指定参数 virtual_host，如果是默认的可以不填。
        connection = pika.BlockingConnection(pika.ConnectionParameters(host = self.host,port = self.port,virtual_host = self.virtual_host,credentials = credentials))
        channel=connection.channel()
        # 声明消息队列，消息将在这个队列传递，如不存在，则创建.
        # queue 声明持久化
        # durable = True 代表消息队列持久化存储，False 非持久化存储
        result = channel.queue_declare(queue = self.queue,durable = True)
        

        currtime = datetime.datetime.now()
        currtime = currtime.strftime("%Y-%m-%d %H:%M:%S")

        projectjson = {
            'project_id':10,
            'app_id':'wxff92ea6443261eee',
            'secret':'1e62fba4dac15df3ffe12373a49a89dc',
            'redis_url':REDIS_STORE_URL,#动态设置
        }
        msgtype = {
            'code':'wechat',
            'type':'template',
            'title':'模板消息',
            'url':None,
            'mini_program':None,
            'template_id':'m7XCd6F0e3CGC_if1U7p4pZXckLObzYXlLA0h_02uVk'
        }
        messagejson = {
            'first':{'value':'预警通知','color':'#173177'},
            'keyword1':{'value':'IT科技 - IT软件与服务','color':'#173177'},
            'keyword2':{'value':currtime,'color':'#173177'},
            'remark':{'value':'感谢使用','color':'#173177'},
        }
        touser = 'orN6Y0WQl5X9dnAUD19KVAV5Vy9s'
        message = json.dumps({'projectjson':projectjson,'createtime':currtime,'messagejson':messagejson,'touser':touser,'msgtype':msgtype})
        print(message)
        # logging.info('------msg----')
        # logging.info(message)
        # 声明exchange，由exchange指定消息在哪个队列传递，如不存在，则创建。durable = True 代表exchange持久化存储，False 非持久化存储
        channel.exchange_declare(exchange = self.exchange,durable = True, exchange_type='topic')
        # channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message,properties=pika.BasicProperties(delivery_mode = 2))
        channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message)
        connection.close()
    #使用临时队列   MQ默认建立的是临时 queue 和 exchange，如果不声明持久化，一旦 rabbitmq 挂掉，queue、exchange 将会全部丢失。所以我们一般在创建 queue 或者 exchange 的时候会声明 持久化。     
    def linshi_que(self):
        credentials = pika.PlainCredentials(self.user, self.pwd)  # mq用户名和密码
        # 虚拟队列需要指定参数 virtual_host，如果是默认的可以不填。
        connection = pika.BlockingConnection(pika.ConnectionParameters(host = self.host,port = self.port,virtual_host = self.virtual_host,credentials = credentials))
        channel=connection.channel()
        # 声明消息队列，消息将在这个队列传递，如不存在，则创建.
        # queue 声明持久化
        # durable = True 代表消息队列持久化存储，False 非持久化存储
        result = channel.queue_declare(queue = self.queue)
        

        currtime = datetime.datetime.now()
        currtime = currtime.strftime("%Y-%m-%d %H:%M:%S")
        message=json.dumps({'OrderId':currtime})
        print(message)
        channel.basic_publish(exchange = self.exchange,routing_key = self.routing_key,body = message)
        # for i in range(10):
        #     message=json.dumps({'OrderId':"1000%s"%i})
        #     # 向队列插入数值 routing_key是队列名
        #     channel.basic_publish(exchange = '',routing_key = 'python-test',body = message)
        #     print(message)
        connection.close()
    
if __name__ == "__main__":
    
    mqc = MqServer(1,3)
    mqc.start()



    

    
